package org.framework.common.ext.util;

import org.apache.commons.lang3.StringUtils;
import org.framework.common.api.support.constant.SystemConstants;

public class SystemUtils {
	
	/**
	 * 获取最大版本号.
	 * eg: VER.2016.1.0
	 * @param prefix
	 * @param version
	 * @param serial
	 * @return
	 * @author chanlong(陈龙)
	 * @date 2016年3月10日 下午12:47:06
	 */
	public static String maxversion(final String prefix, final String version, final String serial){
		String year = CalendarUtils.currentYear("");
		
		if(StringUtil.isEmpty(version)){
			return createVersion(prefix, year, serial);
		}else{
			String[] strs = StringUtils.split(version, SystemConstants.SYMBOL_DOT);
			int min = Integer.valueOf(strs[strs.length-1]);
			int max = Integer.valueOf(strs[strs.length-2]);
			// 同年小版本自增
			if(year.equals(strs[strs.length-3])) {
				min++;
			}
			// 跨年大版本自增
			else {
				min*=0;
				max++;
			}
			return createVersion(prefix, year, new StringBuilder(String.valueOf(max)).append(SystemConstants.SYMBOL_DOT).append(min).toString());
		}
	}

	/**
	 * 获取最大编码.
	 * @param prefix
	 * @param code
	 * @param defnum
	 * @return
	 * @author chanlong(陈龙)
	 * @date 2016年1月23日 下午7:07:16
	 */
	public static String maxcode(final String prefix, final String code, final String serial){
		int currentYear = CalendarUtils.currentYear(0);
		int currentMonth = CalendarUtils.currentMonth(0);
		if(StringUtil.isEmpty(code)){
			return createCode(prefix, currentYear, currentMonth, serial);
		}else{
			int year = Integer.valueOf(code.substring(3,7));
			int month = Integer.valueOf(code.substring(7,9));
			int number = Integer.valueOf(code.substring(9,13));
			if(year == currentYear && month == currentMonth){
				return createCode(prefix, year, month, ++number, serial.length());
			}else if(year == currentYear){
				return createCode(prefix, year, ++month, serial);
			}else{
				return createCode(prefix, ++year, month, serial);
			}
		}
	}
	
	private static String createVersion(final String prefix, final String year, final String serial){
		return new StringBuilder(prefix).append(year).append(SystemConstants.SYMBOL_DOT).append(serial).toString();
	}
	
	/* 创建编码 */
	private static String createCode(final String prefix, final int year, final int month, final int serial, final int length){
		String number = StringUtil.zeroize(serial, StringUtil.ASPECT_PREFIX, length);
		return createCode(prefix, year, month, number);
	}
	
	/* 创建编码 */
	private static String createCode(final String prefix, final int year, final int month, final String serial){
		String months = StringUtil.zeroize(month, StringUtil.ASPECT_PREFIX, 2);
		return new StringBuilder(prefix).append(year).append(months).append(serial).toString();
	}
	
	public static void main(String[] args) {
		System.out.println(maxcode("KH-","KH-2016010001","0001"));
		System.out.println(maxversion("VER.",null,"1.0"));
		//System.out.println(maxversion("VER.","","1.0"));
	}
}
